package com.sugon.controller.module;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.DataFilter;
import com.sugon.annotation.NonBusinessParamValid;
import com.sugon.entity.ModuleRepairRocordEntity;
import com.sugon.entity.ModuleReplacePartEntity;
import com.sugon.modules.base.model.vo.BaseApproveParamVO;
import com.sugon.modules.mold.consts.MoldPmTicketProgressConst;
import com.sugon.modules.mold.consts.MoldReplacePartProgress;
import com.sugon.modules.mold.service.IMoldRepairRecordManager;
import com.sugon.service.ModuleRepairRocordService;
import com.sugon.service.ModuleReplacePartService;
import com.sugon.service.SysConfigService;
import com.sugon.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 模具报修记录Controller
 *
 * @author sugon
 * @date 2019-08-15 09:07:09
 */
@Controller
@RequestMapping("modulerepairrocord")
public class ModuleRepairRocordController {
    @Autowired
    private ModuleRepairRocordService moduleRepairRocordService;
    @Autowired
    private ModuleReplacePartService moduleReplacePartService;
    @Autowired
    private IMoldRepairRecordManager moldRepairRecordManager;
    @Resource
    private SysConfigService configService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("modulerepairrocord:list")
    @DataFilter(deptAlias = "WORKSHOP", userAlias = {"REPORT", "ORDER_EXECUTE_USER"})
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ModuleRepairRocordEntity> moduleRepairRocordList = moduleRepairRocordService.queryList(query);
        int total = moduleRepairRocordService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(moduleRepairRocordList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @AutoLog("提交审核-模具维修换件")
    @RequestMapping("/commitApprove")
    @RequiresPermissions("modulerepairrocord:commitCheck")
    @ResponseBody
    public R commitApprove(@RequestParam String id) {
        // 校验是否存在
        ModuleRepairRocordEntity moduleRepairRocord = moduleRepairRocordService.queryObject(id);
        if (moduleRepairRocord == null) {
            return R.error("模具维修工单不存在，请确认!");
        }
        // 校验是否审核中
        int progress = moduleRepairRocord.getProgress();
        if (progress != MoldReplacePartProgress.NEW && progress != MoldReplacePartProgress.NOT_PASSED) {
            return R.error("模具维修工单审核中或已通过审核，无需重复提交!");
        }
        // 校验是否已填充内容e
        List<ModuleReplacePartEntity> list = moduleReplacePartService.queryList(moduleRepairRocord.getMoldId(), 1, moduleRepairRocord.getRepairCode());
        if (CollectionUtil.isEmpty(list)) {
            return R.error("请在添加换件记录后再提交审核！");
        }
        return moldRepairRecordManager.commitApprove(moduleRepairRocord) ? R.ok() : R.error("提交失败，请稍后重试!");
    }

    /**
     * 车间授权人审批
     */
    @NonBusinessParamValid
    @AutoLog("车间授权人审批")
    @RequestMapping("/deptCheck")
    @RequiresPermissions("modulerepairrocord:deptCheck")
    @ResponseBody
    public R deptCheck(@Validated @RequestBody BaseApproveParamVO approveParam, BindingResult bindingResult) {
        approveParam.setProcessItem(ProcessInfoEnum.MOLD_REPAIR_RP);
        return moldRepairRecordManager.workshopApprove(approveParam) ? R.ok() : R.error();
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("modulerepairrocord:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        ModuleRepairRocordEntity moduleRepairRocord = moduleRepairRocordService.queryObject(id);

        return R.ok().put("moduleRepairRocord", moduleRepairRocord);
    }

    /**
     * 保存
     */
    @AutoLog("模具紧急故障报修")
    @RequestMapping("/save")
    @RequiresPermissions("modulerepairrocord:save")
    @ResponseBody
    public R save(@RequestBody ModuleRepairRocordEntity moduleRepairRocord) {
        moduleRepairRocord.setReport(ShiroUtils.getUserRealName());
        moduleRepairRocord.setWorkshop(ShiroUtils.getWorkshop());
        return moldRepairRecordManager.callRepair(moduleRepairRocord) ? R.ok() : R.error();
    }

    /**
     * 保存-执行
     */
    @AutoLog("模具报修记录--保存")
    @RequestMapping("/updateStaus")
    @ResponseBody
    public R updateStaus(@RequestBody ModuleRepairRocordEntity moduleRepairRocord) {
        moduleRepairRocordService.doRepair(moduleRepairRocord);
        return R.ok();
    }

    /**
     * 修改
     */
    @AutoLog("模具报修记录--修改")
    @RequestMapping("/update")
    @RequiresPermissions("modulerepairrocord:update")
    @ResponseBody
    public R update(@RequestBody ModuleRepairRocordEntity moduleRepairRocord) {
        moduleRepairRocordService.update(moduleRepairRocord);
        return R.ok();
    }

    /**
     * 删除
     */
    @AutoLog("模具报修记录--删除")
    @RequestMapping("/delete")
    @RequiresPermissions("modulerepairrocord:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        moduleRepairRocordService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<ModuleRepairRocordEntity> list = moduleRepairRocordService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 判断工单是否完成状态
     */
    @RequestMapping("/queryIsEnd/{moduleId}")
//    @RequiresPermissions("modulerepairrocord:isEnd")
    @ResponseBody
    public R queryIsEnd(@PathVariable("moduleId") String id) {
        ModuleRepairRocordEntity moduleRepairRocord = moduleRepairRocordService.queryObject(id);
        Integer isEnd = moduleRepairRocord.getStatus();

        return R.ok().put("isEnd", isEnd);
    }

    @RequestMapping("/endProcess/{id}")
    @ResponseBody
    @AutoLog("更新为完成状态")
    public R End(@PathVariable("id") String id) {
        moduleRepairRocordService.updateStatus(id);
        return R.ok();
    }

    @RequestMapping("/confirmRepair")
    @ResponseBody
    @AutoLog("模修工确认开始维修")
    public R confirmRepair(@RequestParam String id) {
        ModuleRepairRocordEntity repairRecord = moduleRepairRocordService.queryObject(id);
        if (repairRecord == null) {
            return R.error("模具紧急维护信息不存在！");
        }
        // 校验工单状态
        if (repairRecord.getStatus() != MoldPmTicketProgressConst.DISPATCH) {
            return R.error("只能确认开始维修处于[待派工]状态的工单！");
        }
        repairRecord.setOrderExecuteUser(ShiroUtils.getUserId());
        return moldRepairRecordManager.confirmRepair(repairRecord) ? R.ok() : R.error();
    }

    @AutoLog("完善维修记录")
    @RequestMapping("/addRepairRecord")
    @ResponseBody
    public R addRepairRecord(@RequestBody ModuleRepairRocordEntity repairRecordParam) {
        // 校验维修工单是否存在
        String maintenRecordId = repairRecordParam.getId();
        ModuleRepairRocordEntity moldRepairTicket = moduleRepairRocordService.queryObject(maintenRecordId);
        if (moldRepairTicket == null) {
            return R.error("工单信息不存在，请确认！");
        }
        // 如果工单执行人未空，则设置为当前更新记录的用户
        if (StrUtil.isEmpty(repairRecordParam.getOrderExecuteUser())) {
            repairRecordParam.setOrderExecuteUser(ShiroUtils.getUserId());
        }
        return moduleRepairRocordService.update(repairRecordParam) > 0 ? R.ok() : R.error("添加维修记录失败！");
    }

    @RequestMapping("/endError")
    @ResponseBody
    @AutoLog("结束紧急维护工单维修")
    public R endError(@RequestParam String id) {
        ModuleRepairRocordEntity moldMaintenanceTicket = moduleRepairRocordService.queryObject(id);
        if (moldMaintenanceTicket == null) {
            return R.error("工单信息不存在，请确认！");
        }
        // 校验工单状态
        if (moldMaintenanceTicket.getStatus() != MoldPmTicketProgressConst.START_REPAIR) {
            return R.error("只可以完成处于[维修中]的工单！");
        }
        // 只可以确认开始维修指派给自己的工单
//        if (!ShiroUtils.getUserId().equals(moldMaintenanceTicket.getOrderExecuteUser())) {
//            return R.error("只可以完成分配给自己的工单!");
//        }
        return moldRepairRecordManager.completeRepair(moldMaintenanceTicket) ? R.ok() : R.error();
    }

    @RequestMapping("/doAction")
    @ResponseBody
    @RequiresPermissions("modulerepairrocord:doAction")
    @AutoLog("执行")
    public R doAction(String id) {
//        moduleRepairRocordService.Urge(id);
        return R.ok();
    }


    @RequiresPermissions("modulerepairrocord:export")
    @RequestMapping("/export")
    @ResponseBody
    public void export(@RequestParam Map<String, Object> params, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
        // 设置导出EXCEL模板名称
        modelMap.put(TemplateExcelConstants.FILE_NAME, "模具维修记录导出_" + cn.hutool.core.date.DateUtil.format(cn.hutool.core.date.DateUtil.date(), "yyyyMMdd"));
        // 设置导出模板参数
        TemplateExportParams templateExportParams = new TemplateExportParams(configService.getPoiTemplatePath() + "moldRepairTicketTemplate.xlsx");
        templateExportParams.setColForEach(true);
        modelMap.put(TemplateExcelConstants.PARAMS, templateExportParams);
        // 获取设备维护计划预览模板数据
        Map<String, Object> mapData = cn.hutool.core.map.MapUtil.newHashMap(1);
        // 获取预防性维护计划数据
        // 维修开始时间
        String beginTime = cn.hutool.core.map.MapUtil.getStr(params, "startDate");
        if (StrUtil.isNotEmpty(beginTime)) {
            params.put("startDate", cn.hutool.core.date.DateUtil.formatDateTime(cn.hutool.core.date.DateUtil.beginOfDay(cn.hutool.core.date.DateUtil.parseDate(beginTime))));
        }
        // 维修终止时间
        String endTime = MapUtil.getStr(params, "endDate");
        if (StrUtil.isNotEmpty(endTime)) {
            params.put("endDate", cn.hutool.core.date.DateUtil.formatDateTime(cn.hutool.core.date.DateUtil.endOfDay(DateUtil.parseDate(endTime))));
        }
        params.put("delFlag", 1);
        mapData.put("list", moduleRepairRocordService.prepareExportData(params));
        modelMap.put(TemplateExcelConstants.MAP_DATA, mapData);
        PoiBaseView.render(modelMap, request, response, TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

}
